// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.common;

import com.alibaba.fastjson.JSON;
import com.liuxinlong.api.SPOInterface;
import com.liuxinlong.api.SharePoint;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.enums.FileBusinessTypeEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.UserGroupDao;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.entity.UserGroup;
import com.liuxinlong.modules.mapper.SharePointHeaderMapper;
import com.liuxinlong.utils.ThreadlocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 导入数据处理类
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年1月23日
 */
@Service
@Slf4j
public class UploadService {
    @Autowired
    private FileManageDao fileManageDao;

    @Autowired
    private SPOInterface spoInterface;

    @Autowired
    private SharePointHeaderMapper sharePointHeaderMapper;

    @Autowired
    private UserGroupDao userGroupDao;

    @Autowired
    private SharePoint sharePoint;

    private static String LOCAL_FILE_PATH = "upload/";

    public UploadResp uploadCsv(MultipartRequest multipartRequest) {
        UploadResp resp = new UploadResp();
        List<Map<String, Object>> list = new ArrayList<>();
        if (list.isEmpty()) {
            resp.setRetCode(ReturnCodes.HTTP_IMPORT_FAIL_UPLOAD_FILE.getRetCode());
            resp.setRetMessage(ReturnCodes.HTTP_IMPORT_FAIL_UPLOAD_FILE.getMsg());
            return resp;
        }
        Map<String, Object> map = list.get(0);
        resp.setFileName((String) map.get("fileName"));
        return resp;
    }

    /**
     * 数据导入文件暂存
     *
     * @param multipartRequest
     * @return
     */
    public Map<String, Object> uploadFileLocal(MultipartRequest multipartRequest) {
        String filePath = "";
        String targetName = "";
        String originalName = "";
        String fileType = "";
        String thumbnail = "";
        Map<String,Object> otherParameter= new HashMap<>();
        if (((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("otherParameter")) {
            otherParameter = JSON.parseObject(((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("otherParameter")[0]);
        }
        int businessType = Integer.valueOf(
                ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("businessType")[0]);
        String groupId = "";
        if (((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("group")) {
            groupId = ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("group")[0];
        }
        UserGroup userGroup;
        if (StringUtils.isNotEmpty(groupId)) {
            userGroup  = userGroupDao.selectById(groupId);
        } else {
            userGroup = userGroupDao.getDefault();
        }
        FileManage fileManage = new FileManage();
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        try {
            // 目标路径
            File file = new File(LOCAL_FILE_PATH);
            // 如果文件目录不存在，就执行创建
            if (!file.isDirectory()) {
                file.mkdirs();
            }

            Iterator<String> fileListIterator = multipartRequest.getFileNames();
            MultipartFile multipartFile;

            while (fileListIterator.hasNext()) {
                // 目标文件名称
                String str = (String) fileListIterator.next();
                multipartFile = multipartRequest.getFile(str);
                originalName = multipartFile.getOriginalFilename();
                fileType = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
                targetName = SnowFlake.nextIdStr();
                filePath = LOCAL_FILE_PATH + targetName + "." + fileType;
                // 创建目标文件
                File targetFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(targetFile);

                // 获取本地文件输入流
                InputStream stream = multipartFile.getInputStream();

                // 写入目标文件
                byte[] buffer = new byte[1024 * 1024];
                int byteRead = 0;
                while ((byteRead = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteRead);
                    fos.flush();
                }
                fos.close();
                stream.close();
                // 添加文件管理记录信息
                fileManage.setId(targetName);
                fileManage.setName(originalName);
                fileManage.setBusinessType(businessType);
                fileManage.setFileType(fileType);
                fileManage.setFilePath(filePath);
                fileManage.setOperateUser(operateUser.getId());
                fileManageDao.insert(fileManage);
            }
        } catch (Exception e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("fileRealPath", filePath);
        resultMap.put("fileName", targetName);
        resultMap.put("realName", originalName);
        resultMap.put("fileType", fileType);
        resultMap.put("thumbnail", thumbnail);
        resultMap.put("approve", ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("approve") ? ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("approve")[0] : null);
        resultMap.put("mocType", ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("mocType") ? ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("mocType")[0] : null);
        resultMap.put("remark", ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().containsKey("remark") ? ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("remark")[0] : null);
        resultMap.put("otherParameter",otherParameter);
        return resultMap;
    }

    /**
     * 批量导入文件
     *
     * @param multipartRequest 请求信息
     * @return  文件路径列表
     */
    public List<FileManage> batchUploadFileLocal(MultipartRequest multipartRequest) {
        User operateUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        List<FileManage> fileMList= new ArrayList<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        try {
            // 目标路径
            File file = new File(LOCAL_FILE_PATH);
            // 如果文件目录不存在，就执行创建
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            MultiValueMap map = multipartRequest.getMultiFileMap();
            List<MultipartFile> list = (List<MultipartFile>) map.get("files");

            for(MultipartFile mFile : list) {
                String originalName = mFile.getOriginalFilename();
                String fileType = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
                String targetName = SnowFlake.nextIdStr();
                String filePath = LOCAL_FILE_PATH + targetName + "." + fileType;
                // 创建目标文件
                File targetFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(targetFile);

                // 获取本地文件输入流
                InputStream stream = mFile.getInputStream();

                // 写入目标文件
                byte[] bytes = mFile.getBytes();//获取字节数组
                fos.write(bytes);
                fos.flush();
                fos.close();
                stream.close();
                // 添加文件管理记录信息
                FileManage fileManage = new FileManage();
                fileManage.setId(targetName);
                fileManage.setName(originalName);
                fileManage.setBusinessType(FileBusinessTypeEnum.ECN_ATTACH.getValue());
                fileManage.setFileType(fileType);
                fileManage.setFilePath(filePath);
                fileManage.setOperateUser(operateUser.getId());
                fileMList.add(fileManage);

            }
        } catch (Exception e) {
            log.error("读取文件失败" + e.getStackTrace());
            throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE);
        }
        fileManageDao.insertBatch(fileMList);

        return fileMList;
    }
}
